package net.hserver.hp_client.ui.home;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import net.hserver.hp_client.R;
import net.hserver.hp_client.config.ConstConfig;
import net.hserver.hp_client.service.ProxyService;
import net.hserver.hp_client.util.DateUtil;
import net.hserver.hp_client.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private static Spinner spinner;

    private List<String> list = new ArrayList<>();

    private static TextView portMsg;
    private static Context context;

    private int remotePort = -1;

    private Button start;

    private ArrayAdapter<String> stringArrayAdapter;

    private ChatMessageReceiver chatMessageReceiver;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        doRegisterReceiver();
        context=getContext();
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final EditText local_ip = root.findViewById(R.id.local_ip);
        final EditText local_port = root.findViewById(R.id.local_port);

        String ip = SharedPreferencesUtil.getString(getContext(), ConstConfig.USER_IP, null);
        String port = SharedPreferencesUtil.getString(getContext(), ConstConfig.USER_PORT, null);
        local_port.setText(port);
        local_ip.setText(ip);

        start = root.findViewById(R.id.start);
        ListView listView = root.findViewById(R.id.listView);
        portMsg = root.findViewById(R.id.port_msg);
        spinner = root.findViewById(R.id.spinner);
        stringArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, list);
        listView.setAdapter(stringArrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                if (ConstConfig.USER_VO != null && ConstConfig.USER_VO.getPorts() != null) {
                    List<Integer> ports = ConstConfig.USER_VO.getPorts();
                    remotePort = ports.get(pos);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (start.getText().toString().equals("开始穿透")) {
                    start.setText("停止穿透");
                    String s = local_ip.getText().toString();
                    String s1 = local_port.getText().toString();
                    if (s.trim().length() > 0 && s1.trim().length() > 0) {
                        SharedPreferencesUtil.putString(getContext(), ConstConfig.USER_IP, s);
                        SharedPreferencesUtil.putString(getContext(), ConstConfig.USER_PORT, s1);
                        Intent intent = new Intent(getContext(), ProxyService.class);
                        intent.putExtra("localIp", s);
                        intent.putExtra("localPort", s1);
                        intent.putExtra("remotePort", String.valueOf(remotePort));
                        getActivity().startService(intent);
                    } else {
                        Toast.makeText(getContext(), "参数 错误" + remotePort, Toast.LENGTH_LONG).show();
                    }
                } else {
                    start.setText("开始穿透");
                    getActivity().stopService(new Intent(getContext(), ProxyService.class));
                }
            }
        });
        setSpData();
        return root;
    }

    public static void setSpData() {
        try {
            if (ConstConfig.USER_VO != null) {
                if (ConstConfig.USER_VO.getPorts() != null && ConstConfig.USER_VO.getPorts().size() > 0) {
                    List<Integer> ports = ConstConfig.USER_VO.getPorts();
                    ArrayAdapter<Integer> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, ports);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner.setAdapter(adapter);
                } else {
                    portMsg.setText("动态分配端口模式");
                }
            }
        }catch (Throwable ignored){}
    }




    private class ChatMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            while (list.size() > 50) {
                list.remove(list.size() - 1);
            }
            String s = intent.getStringExtra("message");
            try {
                if (s != null && s.trim().length() > 0) {
                    list.add(0, DateUtil.getNowDate() + "\n" + s);
                }
            } catch (Exception ignored) {
            }
            String status = intent.getStringExtra("status");
            if (status != null && status.length() > 0) {
                if (Boolean.valueOf(status)) {
                    list.add(0, DateUtil.getNowDate() + "\n" + "穿透心跳提示：已成功连接到云端");
                    start.setText("停止穿透");
                } else {
                    list.add(0, DateUtil.getNowDate() + "\n" + "穿透心跳提示：未连接");
                    start.setText("开始穿透");
                }
            }
            stringArrayAdapter.notifyDataSetChanged();
        }
    }


    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        getActivity().registerReceiver(chatMessageReceiver, filter);
    }

    public void close() {
        try {
            getActivity().unregisterReceiver(chatMessageReceiver);
        } catch (Throwable e) {
        }
    }

    @Override
    public void onDestroyView() {
        close();
        Log.e("---", "关闭");
        super.onDestroyView();
    }

}